import cookie from 'js-cookie';
import { routerRedux } from 'dva/router';
import * as auth from '../services/auth';

export default {

  namespace: 'auth',

  state: {
    error: null,
    qiniuToken: null,
    userInfo: {
      id: '',
      role: {
        id: 0,
        name: '',
        code: 0,
        level: '',
      },
      username: '',
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    },
  },

  effects: {
    *login({ payload }, { call, put }) {
      const data = yield call(auth.login, payload);
      if (data) {
        if (data.err) {
          // TO-DO
          alert('密码错误'); //eslint-disable-line
          return;
        }
        yield put({
          type: 'loginSuccess',
          payload: data.results,
        });
        cookie.set('username', data.username);
        // 进行页面跳转
        yield put(routerRedux.push('/example'));
      }
    },
    *logout({ payload }, { call, put }) { //eslint-disable-line
      cookie.remove('userInfo');
      yield put(routerRedux.push('/login'));
    },
  },

  reducers: {
    loginSuccess(state, action) {
      return { userInfo: { ...action.payload }, error: null };
    },
  },

};
